package com.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Configuration
public class DataSourceConfig {
    @Value("${c3p0.user:#{null}}")
    private String username;
    @Value("${c3p0.password:#{null}}")
    private String password;
    @Value("${c3p0.jdbcUrl:#{null}}")
    private String jdbcUrl;
    @Value("${config.path:#{null}}")
    private String configPath;

    //指定当前对象作为bean
    @Bean(name = "dataSource")
    //指定dataSource来DI
    @Qualifier(value = "dataSource")
    //primary将当前数据库连接池作为默认数据库连接池
    @Primary
    //在application.properties文件中增加前缀c3p0
    @ConfigurationProperties(prefix = "c3p0")
    public DataSource dataSource() throws IOException {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class);
        if(username == null || password == null || jdbcUrl  == null) {
            Properties properties = new Properties();
            InputStream in = null;
            try {
                in = new FileInputStream(configPath);
                properties.load(in);
                dataSourceBuilder.url(properties.getProperty("mysql.jdbcUrl"));
                dataSourceBuilder.username(properties.getProperty("mysql.username"));
                dataSourceBuilder.password(properties.getProperty("mysql.password"));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                in.close();
            }
        }
        return dataSourceBuilder.build();
    }
}
